//! 存储模块
//!
//! 各模块在收到存储信息后，将自己的信息进行序列化并发送给game进行存储
//!
use the_world_game_derive::*;
use the_world_game_core::{
    Handler, service_send_msg,
    result::Result,
};
use crate::game::game_core::Game;
use crate::location::LocationManager;

static BARRAGE: usize = 0;

// locationManager的存储key
static LOCATION: &str = "location";

/// 这个消息是发送Game协程，携带其他协程需要它进行存储的消息
#[derive(Message)]
pub struct GameStoreMsg {
    key: &'static str,
    val: Vec<u8>,
}

impl Handler<GameStoreMsg> for Game {
    fn handle(&mut self, msg: GameStoreMsg) -> Result<()> {
        if let Some(v) = self.store.get_mut(&msg.key) {
            *v = msg.val;
        } else {
            self.store.insert(msg.key, msg.val);
        }
        self.handle_store_set.insert(msg.key);
        if self.handle_store_set.len() == BARRAGE {
            // 写入文件
            // 置零
            self.handle_store_set.clear();
        }
        Ok(())
    }
}

// 这个消息会发送给需要进行存储新的协程
#[derive(Message)]
pub struct StoreNoticeMsg;

// 下面是各个协程特殊处理自己存储的代码
impl Handler<StoreNoticeMsg> for LocationManager {
    fn handle(&mut self, _msg: StoreNoticeMsg) -> Result<()> {
        // 序列化
        let encoded = bincode::serialize(self).unwrap();
        // 发送信息
        service_send_msg::<Game, GameStoreMsg>(GameStoreMsg { key: LOCATION, val: encoded });
        Ok(())
    }
}



